package com.youxin.cpcenter.service.impl;

import java.util.List;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.youxin.busfoundation.bean.BusinessMessages;
import com.youxin.busfoundation.bean.ResponseObject;
import com.youxin.busfoundation.bean.ent.RequestSwitchBean;
import com.youxin.busfoundation.bean.ent.ResponseAccountBean;
import com.youxin.busfoundation.bean.ent.ResponseAccountsBean;
import com.youxin.busfoundation.bean.login.RequestLoginBean;
import com.youxin.busfoundation.bean.login.RequestLoginVerifyCode;
import com.youxin.busfoundation.bean.login.RequestRefreshToken;
import com.youxin.busfoundation.bean.login.UserInfo;
import com.youxin.busfoundation.common.GlobalConfig;
import com.youxin.busfoundation.common.LoginAuth;
import com.youxin.busfoundation.common.redis.RedisOperator;
import com.youxin.cpcenter.api.AuthApi;
import com.youxin.cpcenter.dao.TbEntMemberInfoMapper;
import com.youxin.cpcenter.dao.TbMemberInfoMapper;
import com.youxin.cpcenter.service.LoginService;
import com.youxin.cpcenter.utils.LoginUtils;
import com.youxin.foundation.utils.ArrayUtils;
import com.youxin.foundation.utils.JsonUtils;

/**
 * 登录接口实现
 * @author yingde.cao
 *
 */
@Service("loginService")
public class LoginServiceImpl extends BaseServiceImpl implements LoginService{	
	@Autowired
	private AuthApi authApi;	
	@Autowired
	private TbEntMemberInfoMapper tbEntMemberInfoMapper;
	@Autowired
	private TbMemberInfoMapper tbMemberInfoMapper;
	
	public ResponseObject login(RequestLoginBean bean,HttpServletResponse httpServletResponse) {		
		ResponseObject responseObject=authApi.login(bean);
		if(responseObject.success())
		{
			try {
				String json=JsonUtils.objectToFasterxmlJsonString(responseObject.getData());				
				UserInfo userInfo=JsonUtils.stringToFasterxmlObject(json, UserInfo.class);
//				
//				List<ResponseAccountBean> accounts=listAccount(userInfo);
//				responseCookie(userInfo.getToken(), httpServletResponse);
//				responseObject.setData(accounts);
				
				setResposne(responseObject,userInfo,userInfo.getToken(),httpServletResponse);

			} catch (Exception e) {
				logger.error("login:", e);
			}
			
		}
		return responseObject;
	}
	
	public void setResposne(ResponseObject responseObject,UserInfo userInfo,String token,HttpServletResponse httpServletResponse){
		ResponseAccountsBean responseAccountsBean=new ResponseAccountsBean();
		List<ResponseAccountBean> accounts=listAccount(userInfo,responseAccountsBean);
		responseCookie(token, httpServletResponse);		
		responseAccountsBean.setAccounts(accounts);
		responseAccountsBean.setToken(token);
		responseObject.setData(responseAccountsBean);
	}

	public ResponseObject refreshToken(RequestRefreshToken bean,HttpServletResponse httpServletResponse) {
		UserInfo userInfo=LoginAuth.getUserInfo();	
		ResponseObject responseObject=authApi.refreshToken(bean);		
		if(responseObject.success())
		{
			try {
				setResposne(responseObject,userInfo,responseObject.getData().toString(),httpServletResponse);
				/*
				List<ResponseAccountBean> accounts=listAccount(userInfo);
				responseCookie(responseObject.getData().toString(), httpServletResponse);				
				ResponseAccountsBean responseAccountsBean=new ResponseAccountsBean();
				responseAccountsBean.setAccounts(accounts);
				responseAccountsBean.setToken(responseObject.getData().toString());
				responseObject.setData(responseAccountsBean);
				*/				
			} catch (Exception e) {
				logger.error("refreshToken:", e);
			}
			
		}
		return responseObject;		
	}

	public ResponseObject requestLoginVerifyCode(RequestLoginVerifyCode bean) throws Exception {
		if(!RedisOperator.isCanGetLoginCode(bean.getMobile()))
		{
			return new ResponseObject(BusinessMessages.VERIFY_CODE_TIME_FREQUENTLY);
		}
		return authApi.verifyCode(bean);
	}
	
	public ResponseObject logout(RequestRefreshToken bean)
	{		
		return authApi.logout(bean);
	}
	
	public ResponseObject switchAccount(RequestSwitchBean bean)
	{
		return LoginUtils.switchAccount(bean, tbMemberInfoMapper, tbEntMemberInfoMapper);
	}
	
	private void responseCookie(String token,HttpServletResponse httpServletResponse)
	{
		Cookie cookie=new Cookie(GlobalConfig.TOKEN_NAME, token);
		cookie.setMaxAge(new Long(GlobalConfig.DEFAULT_REFRESH_SECOND).intValue()*2); 
		cookie.setPath("/");
		httpServletResponse.addCookie(cookie);	
	}
	
	public List<ResponseAccountBean> listAccount(UserInfo userInfo,ResponseAccountsBean responseAccountsBean)
	{
		List<ResponseAccountBean> accounts=tbEntMemberInfoMapper.selectByMemberId(userInfo.getId());	
		if(ArrayUtils.isEmpty(accounts))
		{
			return accounts;
		}
		ResponseAccountBean currentItem=null;
		for(ResponseAccountBean item:accounts){
			
			if(item.getEntMemberId().longValue()==userInfo.getEntMemberId())
			{
				currentItem=item;
				
				break;
			}
		}		
		if(currentItem==null)
		{
			currentItem=accounts.get(0);
		}
		currentItem.setCurrent(1);
		LoginUtils.copyAccountInfo(currentItem, responseAccountsBean);
		return accounts;
	}
	
	public List<ResponseAccountBean> listAccount()
	{
		UserInfo userInfo=LoginAuth.getUserInfo();
		ResponseAccountsBean responseAccountsBean=new ResponseAccountsBean();
		return listAccount(userInfo,responseAccountsBean);
	}
	
	public ResponseObject loginfo()
	{
		return authApi.loginfo();
	}
	
}
